/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test.controllers;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import test.entities.TraderGrade;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import test.controllers.exceptions.IllegalOrphanException;
import test.controllers.exceptions.NonexistentEntityException;
import test.controllers.exceptions.PreexistingEntityException;
import test.entities.Client;
import test.entities.Trader;

/**
 *
 * @author Issam
 */
public class TraderJpaController implements Serializable {

    public TraderJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Trader trader) throws PreexistingEntityException, Exception {
        if (trader.getTraderGradeCollection() == null) {
            trader.setTraderGradeCollection(new ArrayList<TraderGrade>());
        }
        if (trader.getClientCollection() == null) {
            trader.setClientCollection(new ArrayList<Client>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<TraderGrade> attachedTraderGradeCollection = new ArrayList<TraderGrade>();
            for (TraderGrade traderGradeCollectionTraderGradeToAttach : trader.getTraderGradeCollection()) {
                traderGradeCollectionTraderGradeToAttach = em.getReference(traderGradeCollectionTraderGradeToAttach.getClass(), traderGradeCollectionTraderGradeToAttach.getTraderGradePK());
                attachedTraderGradeCollection.add(traderGradeCollectionTraderGradeToAttach);
            }
            trader.setTraderGradeCollection(attachedTraderGradeCollection);
            Collection<Client> attachedClientCollection = new ArrayList<Client>();
            for (Client clientCollectionClientToAttach : trader.getClientCollection()) {
                clientCollectionClientToAttach = em.getReference(clientCollectionClientToAttach.getClass(), clientCollectionClientToAttach.getEmail());
                attachedClientCollection.add(clientCollectionClientToAttach);
            }
            trader.setClientCollection(attachedClientCollection);
            em.persist(trader);
            for (TraderGrade traderGradeCollectionTraderGrade : trader.getTraderGradeCollection()) {
                Trader oldTraderOfTraderGradeCollectionTraderGrade = traderGradeCollectionTraderGrade.getTrader();
                traderGradeCollectionTraderGrade.setTrader(trader);
                traderGradeCollectionTraderGrade = em.merge(traderGradeCollectionTraderGrade);
                if (oldTraderOfTraderGradeCollectionTraderGrade != null) {
                    oldTraderOfTraderGradeCollectionTraderGrade.getTraderGradeCollection().remove(traderGradeCollectionTraderGrade);
                    oldTraderOfTraderGradeCollectionTraderGrade = em.merge(oldTraderOfTraderGradeCollectionTraderGrade);
                }
            }
            for (Client clientCollectionClient : trader.getClientCollection()) {
                Trader oldMatriculeOfClientCollectionClient = clientCollectionClient.getMatricule();
                clientCollectionClient.setMatricule(trader);
                clientCollectionClient = em.merge(clientCollectionClient);
                if (oldMatriculeOfClientCollectionClient != null) {
                    oldMatriculeOfClientCollectionClient.getClientCollection().remove(clientCollectionClient);
                    oldMatriculeOfClientCollectionClient = em.merge(oldMatriculeOfClientCollectionClient);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findTrader(trader.getMatricule()) != null) {
                throw new PreexistingEntityException("Trader " + trader + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Trader trader) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Trader persistentTrader = em.find(Trader.class, trader.getMatricule());
            Collection<TraderGrade> traderGradeCollectionOld = persistentTrader.getTraderGradeCollection();
            Collection<TraderGrade> traderGradeCollectionNew = trader.getTraderGradeCollection();
            Collection<Client> clientCollectionOld = persistentTrader.getClientCollection();
            Collection<Client> clientCollectionNew = trader.getClientCollection();
            List<String> illegalOrphanMessages = null;
            for (TraderGrade traderGradeCollectionOldTraderGrade : traderGradeCollectionOld) {
                if (!traderGradeCollectionNew.contains(traderGradeCollectionOldTraderGrade)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain TraderGrade " + traderGradeCollectionOldTraderGrade + " since its trader field is not nullable.");
                }
            }
            for (Client clientCollectionOldClient : clientCollectionOld) {
                if (!clientCollectionNew.contains(clientCollectionOldClient)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Client " + clientCollectionOldClient + " since its matricule field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<TraderGrade> attachedTraderGradeCollectionNew = new ArrayList<TraderGrade>();
            for (TraderGrade traderGradeCollectionNewTraderGradeToAttach : traderGradeCollectionNew) {
                traderGradeCollectionNewTraderGradeToAttach = em.getReference(traderGradeCollectionNewTraderGradeToAttach.getClass(), traderGradeCollectionNewTraderGradeToAttach.getTraderGradePK());
                attachedTraderGradeCollectionNew.add(traderGradeCollectionNewTraderGradeToAttach);
            }
            traderGradeCollectionNew = attachedTraderGradeCollectionNew;
            trader.setTraderGradeCollection(traderGradeCollectionNew);
            Collection<Client> attachedClientCollectionNew = new ArrayList<Client>();
            for (Client clientCollectionNewClientToAttach : clientCollectionNew) {
                clientCollectionNewClientToAttach = em.getReference(clientCollectionNewClientToAttach.getClass(), clientCollectionNewClientToAttach.getEmail());
                attachedClientCollectionNew.add(clientCollectionNewClientToAttach);
            }
            clientCollectionNew = attachedClientCollectionNew;
            trader.setClientCollection(clientCollectionNew);
            trader = em.merge(trader);
            for (TraderGrade traderGradeCollectionNewTraderGrade : traderGradeCollectionNew) {
                if (!traderGradeCollectionOld.contains(traderGradeCollectionNewTraderGrade)) {
                    Trader oldTraderOfTraderGradeCollectionNewTraderGrade = traderGradeCollectionNewTraderGrade.getTrader();
                    traderGradeCollectionNewTraderGrade.setTrader(trader);
                    traderGradeCollectionNewTraderGrade = em.merge(traderGradeCollectionNewTraderGrade);
                    if (oldTraderOfTraderGradeCollectionNewTraderGrade != null && !oldTraderOfTraderGradeCollectionNewTraderGrade.equals(trader)) {
                        oldTraderOfTraderGradeCollectionNewTraderGrade.getTraderGradeCollection().remove(traderGradeCollectionNewTraderGrade);
                        oldTraderOfTraderGradeCollectionNewTraderGrade = em.merge(oldTraderOfTraderGradeCollectionNewTraderGrade);
                    }
                }
            }
            for (Client clientCollectionNewClient : clientCollectionNew) {
                if (!clientCollectionOld.contains(clientCollectionNewClient)) {
                    Trader oldMatriculeOfClientCollectionNewClient = clientCollectionNewClient.getMatricule();
                    clientCollectionNewClient.setMatricule(trader);
                    clientCollectionNewClient = em.merge(clientCollectionNewClient);
                    if (oldMatriculeOfClientCollectionNewClient != null && !oldMatriculeOfClientCollectionNewClient.equals(trader)) {
                        oldMatriculeOfClientCollectionNewClient.getClientCollection().remove(clientCollectionNewClient);
                        oldMatriculeOfClientCollectionNewClient = em.merge(oldMatriculeOfClientCollectionNewClient);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Short id = trader.getMatricule();
                if (findTrader(id) == null) {
                    throw new NonexistentEntityException("The trader with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Short id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Trader trader;
            try {
                trader = em.getReference(Trader.class, id);
                trader.getMatricule();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The trader with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<TraderGrade> traderGradeCollectionOrphanCheck = trader.getTraderGradeCollection();
            for (TraderGrade traderGradeCollectionOrphanCheckTraderGrade : traderGradeCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Trader (" + trader + ") cannot be destroyed since the TraderGrade " + traderGradeCollectionOrphanCheckTraderGrade + " in its traderGradeCollection field has a non-nullable trader field.");
            }
            Collection<Client> clientCollectionOrphanCheck = trader.getClientCollection();
            for (Client clientCollectionOrphanCheckClient : clientCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Trader (" + trader + ") cannot be destroyed since the Client " + clientCollectionOrphanCheckClient + " in its clientCollection field has a non-nullable matricule field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(trader);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Trader> findTraderEntities() {
        return findTraderEntities(true, -1, -1);
    }

    public List<Trader> findTraderEntities(int maxResults, int firstResult) {
        return findTraderEntities(false, maxResults, firstResult);
    }

    private List<Trader> findTraderEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Trader.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Trader findTrader(Short id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Trader.class, id);
        } finally {
            em.close();
        }
    }

    public int getTraderCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Trader> rt = cq.from(Trader.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
